import 'dart:convert';

import 'package:cool_alert/cool_alert.dart';
import 'package:dio/dio.dart';
import 'package:flui/flui.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:fzcgx_app/common/adapter_utils.dart';
import 'package:fzcgx_app/common/color_utils.dart';
import 'package:fzcgx_app/network/http.dart';
import 'package:fzcgx_app/network/urls.dart';
import 'package:fzcgx_app/router/routes.dart';
import 'package:fzcgx_app/ui/base/base_view_model.dart';
import 'package:fzcgx_app/ui/my/factory/model/factory_environment_model.dart';
import 'package:image_picker/image_picker.dart';

class FactoryEnvironmentViewModel extends BaseViewModel {
  List<FactoryEnvironmentModel> models;
  final picker = ImagePicker();
  TextEditingController nameController = TextEditingController();
  FactoryEnvironmentViewModel() {
    this.setState(ViewState.Loading);
  }
  void requestApi() {
    Http.instance.postList<FactoryEnvironmentModel>('env-gc/index', null,
        onSuccess: (data) {
      if (null != data) {
        models = data;
      } else {
        models = List<FactoryEnvironmentModel>();
      }
      this.setState(ViewState.Success);
    }, onError: (error) {
      this.setState(ViewState.Error);
    }, onFail: (fail) {
      this.setState(ViewState.Error);
    });
  }

  void selectPhoto(BuildContext context, FactoryEnvironmentModel model) async {
    int result = await showModalBottomSheet(
      isScrollControlled: true,
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadiusDirectional.only(
          topStart: Radius.circular(10),
          topEnd: Radius.circular(10),
        ),
      ),
      builder: (BuildContext context) {
        return StatefulBuilder(builder: (context1, state) {
          return IntrinsicWidth(
              stepHeight: 1.0,
              child: SingleChildScrollView(
                child: Container(
                  padding: EdgeInsets.only(
                      bottom: MediaQuery.of(context).viewInsets.bottom),
                  child: Column(
                    children: [
                      Container(
                        color: Color.fromRGBO(240, 240, 248, 1),
                        height: 60,
                        padding: EdgeInsets.symmetric(
                            horizontal: AdapterUtils.getWidth(12)),
                        child: Row(
                          children: <Widget>[
                            Text(
                              '提示',
                              style: TextStyle(
                                  fontSize: AdapterUtils.getSp(16),
                                  color: ColorUtils.defaultColor,
                                  fontWeight: FontWeight.w500),
                            ),
                            Spacer(),
                            InkWell(
                              onTap: () => Routes.goBack(context),
                              child: Icon(Icons.close,
                                  color: ColorUtils.text2Color),
                            )
                          ],
                        ),
                      ),
                      InkWell(
                        onTap: () => Navigator.pop(context, 1),
                        child: Container(
                          color: Colors.white,
                          child: ListTile(
                            title: Text(
                              '从相册选择',
                              style: TextStyle(
                                  fontSize: AdapterUtils.getSp(14),
                                  color: ColorUtils.text1Color,
                                  fontWeight: FontWeight.w400),
                            ),
                          ),
                        ),
                      ),
                      InkWell(
                        onTap: () => Navigator.pop(context, 2),
                        child: Container(
                          color: Colors.white,
                          child: ListTile(
                            title: Text(
                              '拍照',
                              style: TextStyle(
                                  fontSize: AdapterUtils.getSp(14),
                                  color: ColorUtils.text1Color,
                                  fontWeight: FontWeight.w400),
                            ),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ));
        });
      },
    );
    if (result == null) {
      return;
    }
    if (result == 1) {
      getImage(1, model);
    } else {
      getImage(2, model);
    }
  }

  Future<Null> getImage(int source, FactoryEnvironmentModel model) async {
    final selectedFile = await picker.getImage(
        source: source == 1 ? ImageSource.gallery : ImageSource.camera);
    if (selectedFile != null) {
      String path = selectedFile.path;
      var name = path.substring(path.lastIndexOf("/") + 1, path.length);
      //var suffix = name.substring(name.lastIndexOf(".") + 1, name.length);
      FormData formData = new FormData.fromMap({
        "name": "file",
        'enctype': "multipart/form-data",
        "img": await MultipartFile.fromFile(path, filename: name),
      });

      Dio dio = new Dio();
      dio.interceptors
          .add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
        dio.lock();

        var authorization = SpUtil.getString('token');
        options.headers["token"] = authorization;

        dio.unlock();
        return options;
      }));
      var dismiss = FLToast.showLoading(text: '正在上传');
      var respone = await dio.post<String>(
        Urls.debug_base_url + Urls.upload_photo,
        data: formData,
      );
      dismiss();
      if (respone.statusCode == 200) {
        FLToast.success(text: '上传成功');
        Map imgData = jsonDecode(respone.data);
        print('uu:$imgData');

        model.imgs.add(imgData['data']['img']['img']);

        notifyListeners();
      }
    }
  }

  void delPhoto(
      BuildContext context, FactoryEnvironmentModel model, String imagesUrl) {
    CoolAlert.show(
        context: context,
        type: CoolAlertType.confirm,
        title: '提示',
        text: "您确定删除该图片吗？",
        cancelBtnText: '再想想',
        confirmBtnText: '确定',
        confirmBtnColor: Color(0xff15A1FF),
        onConfirmBtnTap: () {
          Routes.goBack(context);
          model.imgs.remove(imagesUrl);
          notifyListeners();
        });
  }

  void postApi(BuildContext context, Function callBack) {
    for (int i = 0; i < models.length; i++) {
      if (models[i].imgs.length == 0) {
        FLToast.showText(text: '请上传${models[i].name}图片');
        return;
      }
    }

    var dismiss = FLToast.loading(text: '正在保存...');
    Http.instance.post(
        'env-gc/img-save',
        {
          'imgs': _getImages(),
        },
        onSuccess: (data) {
          FLToast.showSuccess(text: '保存成功');
          callBack();
          Navigator.pop(context);
        },
        onError: (error) {},
        onFail: (fail) {},
        complete: () {
          dismiss();
        });
  }

  String _getImages() {
    List images = List();
    this.models.forEach((element) {
      images.add(element.toJson());
    });
    return jsonEncode(images);
  }

  void addDepartApi(
    BuildContext context,
  ) {
    if (nameController.text.isEmpty) {
      FLToast.showText(text: '请输入部门名称');
      return;
    }

       Navigator.pop(context);
     var dismiss = FLToast.loading(text: '正在新增...');
    Http.instance.post(
        'env-gc/depart-add',
        {
          'name': nameController.text
        },
        onSuccess: (data) {
          FLToast.showSuccess(text: '新增成功');
          requestApi();
        },
        onError: (error) {},
        onFail: (fail) {},
        complete: () {
          dismiss();
        });
  }
}
